<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>axios</title>
    <style>
        table{
            border-collapse: collapse;
            margin-top: 10px;
        }
        td,th{
            border: 1px solid #cccccc;
            padding: 2px 10px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div>
        年级：<input id="grade">
        <button id="btn">查询</button>
    </div>
    <table>
        <thead>
            <tr>
                <th>学号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>性别</th>
                <th>年级</th>
            </tr>
        </thead>
        <tbody>
            <script id="stus_temp" type="text/html">
                {{each $data item}}
                <tr>
                    <td>{{item.no}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.age}}</td>
                    <td>{{item.gender}}</td>
                    <td>{{item.grade}}</td>
                </tr>
                {{/each}}
            </script>
        </tbody>
    </table>
    <div>
        <p>学号：<input id="no"></p>
        <p>姓名：<input id="stuname"></p>
        <p>年龄：<input id="age"></p>
        <p>性别：<input id="gender"></p>
        <p>年级：<input id="grade2"></p>
        <p><button id="btn_add">添加</button></p>
    </div>
    <script src="../js/artTemplate.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.js"></script>
    <script>
        //添加按钮点击事件
        btn_add.onclick = async function(){
            let params = {
                no:no.value,
                name:stuname.value,
                age:age.value,
                gender:gender.value,
                grade:grade2.value
            }
            // axios.post() 是POST请求
            let {data} = await axios.post('http://127.0.0.1:4000/addStu',params)
            if(data==="ok"){
                alert('添加成功！')
                //调用加载数据的方法
                loadData()
                no.value = ""
                stuname.value = ""
                age.value = ""
                gender.value = ""
                grade2.value = ""
            }else{
                alert('添加失败！')
            }
        }
        //查询按钮点击事件
        btn.onclick = function(){
            //调用加载数据的方法
            loadData()
        }
        //加载数据的方法
        async function loadData(){
            let grade = document.querySelector("#grade").value   //获取年级文本框里面的值
            // axios.get() GET请求
            let {data} = await axios.get('http://127.0.0.1:4000/getStus',{
                params:{
                    grade
                }
            })
            let html= template('stus_temp', data)
            document.querySelector('tbody').innerHTML = html
        }
        //调用加载数据的方法
        loadData()
    </script>
</body>
</html>